<template>
  <el-dialog title="批量导入老师分组" :close-on-click-modal="false" :visible.sync="visible" class="cn-dialog cn-dialog_center" lock-scroll width="600px">
    <el-form label-position="top" label-width="80px">
      <el-form-item label="选择文件">
        <el-upload ref="upload" action="#" :auto-upload="false" :on-change="handleFileChange" :before-remove="handleRemove" :limit="1" :file-list="fileList" accept=".xlsx,.xls" drag>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            将文件拖到此处，或
            <em>点击上传</em>
          </div>
          <div class="el-upload__tip" slot="tip">只能上传xlsx/xls文件，且不超过10MB</div>
        </el-upload>
      </el-form-item>

      <el-form-item label="导入选项">
        <el-checkbox v-model="options.skipDuplicate">跳过重复数据</el-checkbox>
        <el-checkbox v-model="options.updateExisting">更新已存在的分组信息</el-checkbox>
      </el-form-item>

      <!-- 预览数据 -->
      <el-form-item label="数据预览" v-if="previewData.length > 0">
        <el-table :data="previewData.slice(0, 5)" border size="mini" max-height="200">
          <el-table-column prop="teacherName" label="老师姓名" width="120"></el-table-column>
          <el-table-column prop="idCard" label="身份证号码" width="180"></el-table-column>
          <el-table-column prop="group" label="组别" width="120"></el-table-column>
          <el-table-column prop="dataId" label="数据标识" width="150">
            <template slot-scope="scope">
              <span v-if="scope.row.dataId">{{ scope.row.dataId }}</span>
              <el-tag v-else type="info" size="mini">无标识</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status === 'valid' ? 'success' : 'danger'" size="mini">
                {{ scope.row.status === 'valid' ? '有效' : '无效' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
        <div v-if="previewData.length > 5" class="preview-more">还有 {{ previewData.length - 5 }} 条数据...</div>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="importData" :loading="btnLoading" :disabled="!canImport">导 入</el-button>
    </span>
  </el-dialog>
</template>

<script>
import * as XLSX from 'xlsx'

export default {
  data() {
    return {
      visible: false,
      btnLoading: false,
      fileList: [],
      previewData: [],
      options: {
        skipDuplicate: true,
        updateExisting: false
      }
    }
  },
  computed: {
    canImport() {
      return this.fileList.length > 0 && this.previewData.length > 0
    }
  },
  methods: {
    init() {
      this.visible = true
      this.fileList = []
      this.previewData = []
      this.options = {
        skipDuplicate: true,
        updateExisting: false
      }
    },

    handleFileChange(file, fileList) {
      this.fileList = fileList
      if (file.raw) {
        this.parseExcelFile(file.raw)
      }
    },

    handleRemove() {
      this.previewData = []
      return true
    },

    parseExcelFile(file) {
      const reader = new FileReader()
      reader.onload = e => {
        try {
          const data = new Uint8Array(e.target.result)
          const workbook = XLSX.read(data, { type: 'array' })
          const firstSheetName = workbook.SheetNames[0]
          const worksheet = workbook.Sheets[firstSheetName]
          const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 })

          // 跳过标题行，解析数据
          const parsedData = []
          // 使用第二行作为表头（索引为1）
          const headerRow = jsonData[1] || []

          // 判断是简单格式还是完整格式
          const isSimpleFormat = headerRow.length <= 3 || ((headerRow[0] === '老师姓名' || headerRow[0] === '参训人') && (headerRow[1] === '身份证号码' || headerRow[1] === '身份证') && (headerRow[2] === '组别名称' || headerRow[2] === '组别'))

          // 从第三行开始解析数据（跳过第一行标题和第二行表头）
          for (let i = 2; i < jsonData.length; i++) {
            const row = jsonData[i]
            let teacherName, idCard, group, dataId

            if (isSimpleFormat) {
              // 简单格式：老师姓名、身份证、组别
              if (row.length >= 3 && row[0] && row[1] && row[2]) {
                teacherName = String(row[0]).trim()
                idCard = String(row[1]).trim()
                group = String(row[2]).trim()
                dataId = null
              } else {
                continue
              }
            } else {
              // 完整格式：按照导出格式解析（基于第二行表头）
              // 第二行表头：序号、师训名称、校区编号、省份、城市、校区简称、参训人、职位、性别、电话、身份证、组别、参训状态、校区状态、校区阶段、付款时间、付款金额、退款单号、退款金额、签到时间、数据标识（导入需要）
              if (row.length >= 21 && row[6] && row[10] && row[11]) {
                teacherName = String(row[6]).trim() // 参训人（索引6）
                idCard = String(row[10]).trim() // 身份证（索引10）
                group = String(row[11]).trim() // 组别（索引11）
                dataId = row[20] ? String(row[20]).trim() : null // 数据标识（导入需要）（索引20）
              } else {
                continue
              }
            }

            const item = {
              teacherName,
              idCard,
              group,
              dataId,
              status: this.validateRowData(teacherName, idCard, group)
            }
            parsedData.push(item)
          }

          this.previewData = parsedData

          if (parsedData.length === 0) {
            this.$message.warning('文件中没有找到有效数据，请检查文件格式')
          } else {
            this.$message.success(`成功解析 ${parsedData.length} 条数据`)
          }
        } catch (error) {
          console.error('解析文件失败:', error)
          this.$message.error('文件解析失败，请检查文件格式')
        }
      }
      reader.readAsArrayBuffer(file)
    },

    validateRowData(teacherName, idCard, group) {
      // 基本验证
      if (!teacherName || !idCard || !group) {
        return 'invalid'
      }

      // 身份证号码格式验证
      const idCardRegex = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
      if (!idCardRegex.test(idCard)) {
        return 'invalid'
      }

      return 'valid'
    },

    importData() {
      if (!this.canImport) {
        this.$message.warning('请先选择文件并确保数据有效')
        return
      }

      // 过滤有效数据
      const validData = this.previewData.filter(item => item.status === 'valid')

      if (validData.length === 0) {
        this.$message.warning('没有有效的数据可以导入')
        return
      }

      this.btnLoading = true

      // 触发导入事件
      this.$emit('import', {
        data: validData,
        options: this.options
      })
    }
  }
}
</script>

<style lang="scss" scoped>
>>> .el-dialog__body {
  padding: 20px !important;
}

.preview-more {
  text-align: center;
  color: #909399;
  font-size: 12px;
  margin-top: 10px;
}

.el-upload__tip {
  color: #606266;
  font-size: 12px;
  margin-top: 7px;
}
</style>
